package com.academic.system.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.ArrayList;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.academic.system.controller.request.CreateUserRequest;
import com.academic.system.controller.request.ReviewRequest;
import com.academic.system.model.User;
import com.academic.system.model.UserRole;
import com.academic.system.model.Paper;
import com.academic.system.model.VerticalProject;
import com.academic.system.model.HorizontalProject;
import com.academic.system.security.UserDetailsImpl;
import com.academic.system.service.UserService;
import com.academic.system.repository.PaperRepository;
import com.academic.system.repository.VerticalProjectRepository;
import com.academic.system.repository.HorizontalProjectRepository;

/**
 * 教师专用控制器
 */
@RestController
@RequestMapping("/api/teacher")
@CrossOrigin(origins = "*", maxAge = 3600)
public class TeacherController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private PaperRepository paperRepository;
    
    @Autowired
    private VerticalProjectRepository verticalProjectRepository;
    
    @Autowired
    private HorizontalProjectRepository horizontalProjectRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    /**
     * 获取教师的学生列表
     */
    @GetMapping("/students")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> getMyStudents() {
        // 获取当前登录的教师信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        // 查询该教师的学生
        List<User> students = userService.findStudentsByTeacherId(userDetails.getId());
        
        List<Map<String, Object>> result = students.stream()
            .map(this::convertUserToDto)
            .collect(Collectors.toList());
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 添加学生账号
     */
    @PostMapping("/students")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> addStudent(@Valid @RequestBody CreateUserRequest request) {
        // 获取当前登录的教师信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        // 检查用户名是否已存在
        if (userService.findByUsername(request.getUsername()) != null) {
            return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(Map.of("message", "用户名已存在"));
        }
        
        // 创建学生用户
        User student = new User();
        student.setUsername(request.getUsername());
        student.setPassword(passwordEncoder.encode(request.getPassword()));
        student.setEmail(request.getEmail());
        student.setRealName(request.getRealName());
        student.setRole(UserRole.STUDENT);
        
        // 设置教师关联
        User teacher = userService.findById(userDetails.getId());
        student.setCreator(teacher);
        
        // 保存学生
        User savedStudent = userService.createUser(student);
        
        return ResponseEntity.status(HttpStatus.CREATED).body(convertUserToDto(savedStudent));
    }
    
    /**
     * 删除学生账号
     */
    @DeleteMapping("/students/{id}")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> deleteStudent(@PathVariable Integer id) {
        // 获取当前登录的教师信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        // 查询学生
        User student = userService.findById(id);
        
        if (student == null) {
            return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(Map.of("message", "学生不存在"));
        }
        
        // 验证该学生是否属于当前教师
        if (student.getCreator() == null || !student.getCreator().getId().equals(userDetails.getId())) {
            return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body(Map.of("message", "无权删除非自己的学生"));
        }
        
        // 删除学生
        userService.deleteUser(id);
        
        return ResponseEntity.ok(Map.of("message", "学生已删除"));
    }
    
    /**
     * 更新学生信息
     */
    @PutMapping("/students/{id}")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> updateStudent(@PathVariable Integer id, @Valid @RequestBody Map<String, Object> request) {
        // 获取当前登录的教师信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        // 查询学生
        User student = userService.findById(id);
        
        if (student == null) {
            return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(Map.of("message", "学生不存在"));
        }
        
        // 验证该学生是否属于当前教师
        if (student.getCreator() == null || !student.getCreator().getId().equals(userDetails.getId())) {
            return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body(Map.of("message", "无权更新非自己的学生"));
        }
        
        // 更新学生信息
        if (request.containsKey("realName")) {
            student.setRealName((String) request.get("realName"));
        }
        
        if (request.containsKey("email")) {
            student.setEmail((String) request.get("email"));
        }
        
        if (request.containsKey("department")) {
            student.setDepartment((String) request.get("department"));
        }
        
        // 保存更新后的学生信息
        User updatedStudent = userService.updateUser(student);
        
        return ResponseEntity.ok(convertUserToDto(updatedStudent));
    }
    
    /**
     * 获取待审核的成果列表
     */
    @GetMapping("/achievements/pending")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> getPendingAchievements() {
        // 获取当前登录的教师信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        // 获取该教师学生的待审核成果
        List<User> myStudents = userService.findStudentsByTeacherId(userDetails.getId());
        List<Integer> studentIds = myStudents.stream()
            .map(User::getId)
            .collect(Collectors.toList());
        
        List<Map<String, Object>> allAchievements = new ArrayList<>();
        
        // 获取所有待审核的论文
        List<Paper> pendingPapers = paperRepository.findByApprovalStatus("pending");
        pendingPapers.stream()
            .filter(paper -> paper.getCreator() != null && studentIds.contains(paper.getCreator().getId()))
            .forEach(paper -> allAchievements.add(convertPaperToDto(paper)));
        
        // 获取所有待审核的纵向课题
        List<VerticalProject> pendingVerticalProjects = verticalProjectRepository.findByApprovalStatus("pending");
        pendingVerticalProjects.stream()
            .filter(project -> project.getCreator() != null && studentIds.contains(project.getCreator().getId()))
            .forEach(project -> allAchievements.add(convertVerticalProjectToDto(project)));
        
        // 获取所有待审核的横向课题
        List<HorizontalProject> pendingHorizontalProjects = horizontalProjectRepository.findByApprovalStatus("pending");
        pendingHorizontalProjects.stream()
            .filter(project -> project.getCreator() != null && studentIds.contains(project.getCreator().getId()))
            .forEach(project -> allAchievements.add(convertHorizontalProjectToDto(project)));
        
        return ResponseEntity.ok(allAchievements);
    }
    
    /**
     * 获取已审核的成果列表
     */
    @GetMapping("/achievements/reviewed")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> getReviewedAchievements() {
        // 获取当前登录的教师信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        List<Map<String, Object>> allAchievements = new ArrayList<>();
        
        // 获取该教师审核的论文
        List<Paper> reviewedPapers = paperRepository.findAll().stream()
            .filter(paper -> paper.getApprover() != null && paper.getApprover().getId().equals(userDetails.getId()))
            .collect(Collectors.toList());
        reviewedPapers.forEach(paper -> allAchievements.add(convertPaperToDto(paper)));
        
        // 获取该教师审核的纵向课题
        List<VerticalProject> reviewedVerticalProjects = verticalProjectRepository.findAll().stream()
            .filter(project -> project.getApprover() != null && project.getApprover().getId().equals(userDetails.getId()))
            .collect(Collectors.toList());
        reviewedVerticalProjects.forEach(project -> allAchievements.add(convertVerticalProjectToDto(project)));
        
        // 获取该教师审核的横向课题
        List<HorizontalProject> reviewedHorizontalProjects = horizontalProjectRepository.findAll().stream()
            .filter(project -> project.getApprover() != null && project.getApprover().getId().equals(userDetails.getId()))
            .collect(Collectors.toList());
        reviewedHorizontalProjects.forEach(project -> allAchievements.add(convertHorizontalProjectToDto(project)));
        
        return ResponseEntity.ok(allAchievements);
    }
    
    /**
     * 获取成果详情
     */
    @GetMapping("/achievements/{id}")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> getAchievementById(@PathVariable Integer id) {
        return ResponseEntity
            .status(HttpStatus.NOT_IMPLEMENTED)
            .body(Map.of("message", "请使用新的成果详情API: /api/achievements/{type}/{id}"));
    }
    
    /**
     * 审核成果
     */
    @PutMapping("/achievements/review")
    @PreAuthorize("hasRole('TEACHER')")
    public ResponseEntity<?> reviewAchievement(@Valid @RequestBody ReviewRequest request) {
        return ResponseEntity
            .status(HttpStatus.NOT_IMPLEMENTED)
            .body(Map.of("message", "请使用新的审核API: /api/achievements/{type}/{id}/review"));
    }
    
    /**
     * 将用户实体转换为DTO
     */
    private Map<String, Object> convertUserToDto(User user) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", user.getId());
        dto.put("username", user.getUsername());
        dto.put("email", user.getEmail());
        dto.put("realName", user.getRealName());
        dto.put("role", user.getRole().toString());
        dto.put("department", user.getDepartment());
        
        return dto;
    }
    
    /**
     * 将论文实体转换为DTO
     */
    private Map<String, Object> convertPaperToDto(Paper paper) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", paper.getId());
        dto.put("title", paper.getPaperTitle());
        dto.put("type", "论文");
        dto.put("status", convertStatus(paper.getApprovalStatus()));
        dto.put("createdAt", paper.getSubmissionDate() != null ? paper.getSubmissionDate().toString() : null);
        dto.put("comments", paper.getApprovalComment());
        
        if (paper.getCreator() != null) {
            Map<String, Object> student = new HashMap<>();
            student.put("id", paper.getCreator().getId());
            student.put("username", paper.getCreator().getUsername());
            student.put("realName", paper.getCreator().getRealName());
            dto.put("student", student);
        }
        
        return dto;
    }
    
    /**
     * 将纵向课题实体转换为DTO
     */
    private Map<String, Object> convertVerticalProjectToDto(VerticalProject project) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", project.getId());
        dto.put("title", project.getProjectName());
        dto.put("type", "纵向课题");
        dto.put("status", convertStatus(project.getApprovalStatus()));
        dto.put("createdAt", project.getSubmissionDate() != null ? project.getSubmissionDate().toString() : null);
        dto.put("comments", project.getApprovalComment());
        
        if (project.getCreator() != null) {
            Map<String, Object> student = new HashMap<>();
            student.put("id", project.getCreator().getId());
            student.put("username", project.getCreator().getUsername());
            student.put("realName", project.getCreator().getRealName());
            dto.put("student", student);
        }
        
        return dto;
    }
    
    /**
     * 将横向课题实体转换为DTO
     */
    private Map<String, Object> convertHorizontalProjectToDto(HorizontalProject project) {
        Map<String, Object> dto = new HashMap<>();
        dto.put("id", project.getId());
        dto.put("title", project.getProjectName());
        dto.put("type", "横向课题");
        dto.put("status", convertStatus(project.getApprovalStatus()));
        dto.put("createdAt", project.getSubmissionDate() != null ? project.getSubmissionDate().toString() : null);
        dto.put("comments", project.getApprovalComment());
        
        if (project.getCreator() != null) {
            Map<String, Object> student = new HashMap<>();
            student.put("id", project.getCreator().getId());
            student.put("username", project.getCreator().getUsername());
            student.put("realName", project.getCreator().getRealName());
            dto.put("student", student);
        }
        
        return dto;
    }
    
    /**
     * 转换状态显示
     */
    private String convertStatus(String dbStatus) {
        if (dbStatus == null) return "待审核";
        switch (dbStatus) {
            case "approved": return "已通过";
            case "rejected": return "已拒绝";
            case "pending": 
            default: return "待审核";
        }
    }
} 